from kubernetes import client, config
from typing import Dict, List
from .models import ResourceType

def get_k8s_resources(resource_type: ResourceType, namespace: str = None) -> List[Dict]:
    """查询 Kubernetes 指定资源类型的数据"""
    config.load_kube_config(config_file="/Users/wangxudong/Py/project2/backend/app/kubeconfig")
    
    core_v1 = client.CoreV1Api()
    apps_v1 = client.AppsV1Api()
    
    resource_handlers = {
        "pods": lambda: core_v1.list_namespaced_pod(namespace).items,
        "deployments": lambda: apps_v1.list_namespaced_deployment(namespace).items,
        "services": lambda: core_v1.list_namespaced_service(namespace).items,
        "configmaps": lambda: core_v1.list_namespaced_config_map(namespace).items,
        "secrets": lambda: core_v1.list_namespaced_secret(namespace).items,
        "nodes": lambda: core_v1.list_node().items,
        "namespaces": lambda: core_v1.list_namespace().items,
    }
    
    try:
        resources = resource_handlers[resource_type]()
        return [_format_resource(resource_type, res) for res in resources]
    except Exception as e:
        return [{"error": str(e)}]

def _format_resource(resource_type: str, resource) -> Dict:
    """统一格式化不同资源类型的输出"""
    if resource_type == "pods":
        return {
            "name": resource.metadata.name,
            "namespace": resource.metadata.namespace,
            "status": resource.status.phase,
            "ip": resource.status.pod_ip,
            "node": resource.spec.node_name
        }
    elif resource_type == "deployments":
        return {
            "name": resource.metadata.name,
            "namespace": resource.metadata.namespace,
            "replicas": f"{resource.status.available_replicas}/{resource.spec.replicas}",
            "images": [c.image for c in resource.spec.template.spec.containers]
        }
    # 其他资源类型的格式化逻辑...
    else:
        return {"name": resource.metadata.name, "type": resource_type}